// Plane.cpp
//
//////////////////////////////////////////////////////////////////////

#include "Plane.h"

Plane::Plane(){
	
}

Plane::Plane(Vector3D A, Vector3D B, Vector3D C) {
	CalcCoeffs(A,B,C);
}

void Plane::SetNandD(Vector3D n, float d) {
	N=n;
	D=d; 
}

void Plane::CalcCoeffs(Vector3D A, Vector3D B, Vector3D C){
	N = (B-A) * (C-A);
	N.normalize();   
	D = N.dot(A);    
}

void Plane::CalcCoeffsGivenNormal(Vector3D Normal, Vector3D PtOnPlane){
	N = Normal;
	D = N.dot(PtOnPlane);
}

float Plane::DistToPt(Vector3D P) const {
	return( (N.dot(P))-D );
}

int Plane::InOutTest(Vector3D P) const {
	return( (N.dot(P))>D);
}

int Plane::RayIntersection(Vector3D Start, Vector3D Dir, Vector3D& HitPt) const {
	float Denom = N.dot(Dir);

	if (Denom==(float)0)
		return(0); 

	float Tval = (D-(N.dot(Start))) / Denom;

	if (Tval>=0){
		HitPt = Start + Dir*Tval; 
		return(1);                
	}

	return(0);
}

int Plane::EdgeIntersection(Vector3D A, Vector3D B, Vector3D &HitPt) const {
	Vector3D Dir = B-A; 
	float Denom = N.dot(Dir);

	if (Denom==(float)0)
		return(0); 

	float Tval = (D-(N.dot(A)))/Denom;

	if (Tval>=0 && Tval<=1){
		HitPt = A + Dir*Tval;
		return(1);               
	}

	return(0);
}
